package com.buaa.daas.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.buaa.daas.constant.SaveUserType;
import com.buaa.daas.entity.StuDailyClockMessage;
import com.buaa.daas.entity.StuInfo;
import com.buaa.daas.mapper.StuInfoMapper;
import com.buaa.daas.service.StuInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author WangKangMing
 * @since 2021-06-04
 */
@Service
public class StuInfoServiceImpl extends ServiceImpl<StuInfoMapper, StuInfo> implements StuInfoService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StuInfoMapper stuInfoMapper;

    @Override
    public StuInfo getInfoByRequest(HttpServletRequest request) {
        String token = "";
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if("token".equals(cookie.getName())){
                    token = cookie.getValue();
                }
            }

            if(!StringUtils.isBlank(token)){
                Object tokenValue = redisTemplate.opsForValue().get(token);
                if(tokenValue!=null){
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("stu_num", tokenValue);
                    List<StuInfo> stuInfos = stuInfoMapper.selectByMap(map);
                    if(stuInfos != null && stuInfos.size() >= 1){
                        return stuInfos.get(0);
                    }
                }
            }
        }

        return null;
    }

    @Override
    public int saveNewUser(StuInfo stuInfo) {

        QueryWrapper<StuInfo> stuInfoQueryWrapper = new QueryWrapper<>();
        stuInfoQueryWrapper.eq("stu_num",stuInfo.getStuNum());

        List<StuInfo> stuInfos = stuInfoMapper.selectList(stuInfoQueryWrapper);
        if(stuInfos!=null && stuInfos.size()>=1){
            return SaveUserType.SaveUserTypeEnum.STUNUM_EXISTED.getCode();
        }else{
            //不重复，那么就应该保存这个账号
            int insert = stuInfoMapper.insert(stuInfo);
            return SaveUserType.SaveUserTypeEnum.REGIST_SUCCESS.getCode();
        }

    }

}
